package org.mozhu.mboot.core.web.sitemesh.filter;

import org.sitemesh.content.ContentProcessor;
import org.sitemesh.webapp.WebAppContext;
import org.sitemesh.webapp.contentfilter.ResponseMetaData;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class SpringMVCWebAppContext extends WebAppContext {

    private final ViewResolver viewResolver;

    public SpringMVCWebAppContext(ViewResolver viewResolver, String contentType, HttpServletRequest request,
                                  HttpServletResponse response, ServletContext servletContext,
                                  ContentProcessor contentProcessor, ResponseMetaData metaData,
                                  boolean includeErrorPages) {
        super(contentType, request, response, servletContext, contentProcessor, metaData, includeErrorPages);
        this.viewResolver = viewResolver;
    }

    /**
     * Dispatch to the actual path. This method can be overriden to provide
     * different ways of dispatching (such as cross web-app).
     */
    @Override
    protected void dispatch(HttpServletRequest request, HttpServletResponse response, String path)
            throws ServletException {
        try {
            Locale locale = request.getLocale();
            View view = getViewResolver().resolveViewName(path, locale);
            if (view == null) {
                throw new ServletException("Not found: " + path);
            }
            view.render(null, request, response);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    public ViewResolver getViewResolver() {
        return viewResolver;
    }

}
